<?php

namespace app\home\controller;

use think\Controller;
use think\Db;
use think\Cookie;

class Login extends Controller
{
	// 显示登录模块
	public function login()
	{
		// if (!empty(Cookie('home_msg'))) {
		// 	$info = Db::table('user_home')->field('name')->where(['token' => md5(Cookie('home_msg.token'))])->find();
			
		// 	return $this->success('登陆成功，正在为您跳转...', 'Index/index', 1);
		// }
		return $this->fetch();
	}


	public function checkLogin()
	{
		$validate = validate('Login');

		if (!$validate->scene('msg')->check(input())) {
			// return returnAjax(400, $validate->getError());
		}

		//验证码
		if(!captcha_check(input('verify'))) {
            // return returnAjax(400, '验证码错误');
		}

		$phone = input('phone');
		$password = input('password');
		//查询账号密码是否存在	
		$data = model('Login')->login(['phone' => $phone, 'password' => $password]);
		
		if (!empty($data)) {
			$token = $data['phone'].$_SERVER['REMOTE_ADDR'];
			//cookie
			$msg = ['phone' => $data['phone'], 'token' => $token];

			//判断用户点了记住密码没
		    if (!empty(input('online'))) {
		    	Cookie::set('home_msg', $msg, 3600*24*7, '/');
		    } else {
		        Cookie::set('home_msg', $msg, 0, '/');
		    }

		    //生成token有限期 默认一个礼拜
		    $time = md5(date('Y-m-d H:i:s', time()+3600*24*7));

		    Db::table('user_home')->where('id', $data['id'])->update(['token' => $token, 'update_time' => $time]);

			return returnAjax(200, '登录成功');
		} else {
			return returnAjax(400, '账号密码错误');
		}
	}

	/**
	 * 
	 * @return [type] [description]
	 */
	public function loginOut()
	{
		Cookie::delete('home_msg');
		return $this->success('退出成功，正在为您跳转...', 'Login/login', 1);
	}
}